$NG.AllReady(function (page, { useValuesChange,useDataIndexChange,useUpdateRows,useUpdateRow }) {
    const mstform = $NG.getCmpApi("p_form_track_insert_m")
    const dgrid1 = $NG.getCmpApi("p_form_track_insert_d")  
    useDataIndexChange(({args})=>{//
        const data = args[0]
        getPtInfoByPhid(data.phid_pc,(datas)=>{
            let _map = {};
			if (window._lsz_catch_monthPay) {
				window._lsz_catch_monthPay.forEach((item) => {
					if (data.phid_pc == item.phid_pc) {
						_map = { ...item };
					}
				});
			}
			data.u_ycyc = _map.u_jhhk;
			data.u_yjcykh = _map.u_cyhk;
            data.u_hyjh = _map.u_hyhk
            data.u_devision=datas.division_phid
            data.u_devision_EXName=datas.division_name

            data.u_regional_center = datas.regional_center_phid
            data.u_regional_center_EXName = datas.regional_center_name

            data.u_cpx = datas.midwife_phid
            data.u_cpx_EXName = datas.midwife_name

            data.phid_customer_ent = datas.customer_id
            data.phid_customer_ent_EXName = datas.customer_name
            
            data.u_city = datas.si_phid
            data.u_city_EXName = datas.si_name

            data.u_region = datas.q_phid
            data.u_region_EXName = datas.q_name

            data.u_hydl = datas.hydl_phid
            data.u_hydl_EXName = datas.hydl_name

            if(window._lsz_catch_GivePay&&window._lsz_catch_GivePay[data.phid_pc]&&window._lsz_catch_lcb){
                data.u_ysje = window._lsz_catch_lcb[data.phid_pc] - window._lsz_catch_GivePay[data.phid_pc][mstform.getItem("u_date").getValue().substring(0,7)]
            }
            dgrid1.refreshView()
        })
    },"phid_pc")
    useValuesChange(({args})=>{
        getProjectMonthPay()
        getGivePayForm()
        getLcbjhHkjhDetail()
    },"p_form_track_insert_m.u_date")
    useValuesChange(({args})=>{
      const phid = mstform.getItem("creator").getValue()
      console.log(phid);
      getBasiceTable()
    },"p_form_track_insert_m.creator")
    useUpdateRows(({args})=>{
        sumAmt()
    })
    getBasiceTable()
    async function getBasiceTable(){
      const phid = mstform.getItem("creator").getValue()
      if(!phid) return
      await $NG.execServer("getBasiceTable",{phid},(res)=>{
        console.log(res);
        if(res.count==0) return 
        const _data = JSON.parse(res.data)
        console.log(`回款负责人带出数据`,_data);
        const _temp = []
        _data.forEach(items => {
          const item = items.extendObjects
          _temp.push({
            phid_pc:item.phid_pc,
            phid_pc_EXName:item.phid_name,
            u_devision:item.devision,
            u_devision_EXName:item.devision_exname,
            u_regional_center:item.qyzx,
            u_regional_center_EXName:item.qyzx_name,
            u_cpx:item.cpx,
            u_cpx_EXName : item.cpx_exname,
            u_hklx:item.hklx
          })
          dgrid1.clearRows().then(async ()=>{
            await dgrid1.addRows(_temp)
            const args = dgrid1.getRows()
            //匹配客户经理
            args.forEach(data=>{
                getPtInfoByPhid(data.phid_pc,(datas)=>{
                    let _map = {}
                    if(window._lsz_catch_monthPay){
                        window._lsz_catch_monthPay.forEach((item)=>{
                            if(data.phid_pc == item.phid_pc){
                                _map = {...item}
                            }
                        })
                    }
                    data.u_ycyc = _map.u_jhhk
                    data.u_yjcykh = _map.u_cyhk
                    data.u_hyjh = _map.u_hyhk
                    data.phid_customer_ent = datas.customer_id;
					data.phid_customer_ent_EXName = datas.customer_name;
					data.u_city = datas.si_phid;
					data.u_city_EXName = datas.si_name;

					data.u_region = datas.q_phid;
					data.u_region_EXName = datas.q_name;
                    
                    data.u_hydl = datas.hydl_phid
                    data.u_hydl_EXName = datas.hydl_name
                    //
                    if(window._lsz_catch_GivePay&&window._lsz_catch_GivePay[data.phid_pc]&&window._lsz_catch_lcb){
                        data.u_ysje = window._lsz_catch_lcb[data.phid_pc] - window._lsz_catch_GivePay[data.phid_pc][mstform.getItem("u_date").getValue().substring(0,7)]
                    }
                    dgrid1.refreshView()
                })
            })
          })
        });
      })
    }

    function sumAmt(){
        const _arr = dgrid1.getRows()
        let fxje = 0// 风险金额
        let maxMonthAmt = 0 // 本月最大预计回款金额
        let outDate = ""// 延期月份
        _arr.forEach(item=>{
            item.u_fxje = (Number(item.u_ysje) || 0) - (Number(item.u_byyh) || 0) - (Number(item.u_byzqb) || 0) - (Number(item.u_bykzq) || 0)
            item.u_zdyjhk= (Number(item.u_byyh) || 0) + (Number(item.u_byzqb) || 0) + (Number(item.u_bykzq) || 0)
            try{
                outDate = monthDifference(mstform.getItem("date").getValue(),item.u_dqsj)
            }catch(er){
                outDate = ""
            }
            if(item.u_ysje>=500000){
                item.u_zxxe = (Number(item.u_ysje) || 0)
            }
            item.u_xekyql = (Number(item.u_byyh) || 0)
        })
        dgrid1.refreshView()
    }

    function monthDifference(startDateStr, endDateStr) {
        // 将时间字符串转换为 Date 对象
        const startDate = new Date(startDateStr);
        const endDate = new Date(endDateStr);
    
        // 提取年份和月份
        const startYear = startDate.getFullYear();
        const startMonth = startDate.getMonth();
        const endYear = endDate.getFullYear();
        const endMonth = endDate.getMonth();
    
        // 计算月份差值
        const diff = (endYear - startYear) * 12 + (endMonth - startMonth);
    
        // 向下取整
        return Math.floor(diff);
    }
    //获取预测信息
    getProjectMonthPay()
    function getProjectMonthPay(){
        if(!mstform.getItem("u_date").getValue()){
            $NG.message("您还未选择日期！")
            return
        }
        $NG.execServer("getProjectMonthPay",{month:String(new Date(mstform.getItem("u_date").getValue()).getMonth()+1)},(res)=>{
            console.log(`预测`,res);
            if(res.count == 0 ) {
                window._lsz_catch_monthPay=null
            } else {
                const _data = JSON.parse(res.data)
                console.log(`预测`,_data);
                window._lsz_catch_monthPay=_data.reduce((value,item)=>{
                    value.push(item.extendObjects)
                    return value
                },[])
            }
        })
    }
    getGivePayForm()
    function getGivePayForm(){
        if(!mstform.getItem("u_date").getValue()) return 
        $NG.execServer("getGivePayForm",{},(res)=>{
            console.log(`回收`,res);
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)
            console.log(`回收`,_data);
            window._lsz_catch_GivePay = accumulateData(_data.map(item=>item.extendObjects))
        })
    }
    getLcbjhHkjhDetail()
    function getLcbjhHkjhDetail(){
        if(!mstform.getItem("u_date").getValue()) return 
        $NG.execServer("getLcbjhHkjhDetail",{date:mstform.getItem("u_date").getValue().substring(0,7)},(res)=>{
            console.log(`里程碑`,res);
            if(res.count ==0) return 
            const _data = JSON.parse(res.data)
            window._lsz_catch_lcb =accumulateAmountByProject( _data.map(item=>item.extendObjects))
            console.log(`里程碑`,_data);
        })
    }
    function accumulateAmountByProject(data) {
        const result = {};
        // 遍历对象数组
        data.forEach(item => {
            const { phid_pc, amt } = item;
            // 如果 result 对象中已经存在该项目，则累加金额
            if (result[phid_pc]) {
                result[phid_pc] += amt;
            } else {
                // 如果不存在该项目，则初始化金额
                result[phid_pc] = amt;
            }
        });
        return result;
    }
    //格式化收款单
    function accumulateData(data, baseDate = mstform.getItem("u_date").getValue()) {
        // 解析基准时间，获取年份和月份
        const baseYear = new Date(baseDate).getFullYear();
        const baseMonth = new Date(baseDate).getMonth() + 1;
    
        let result = null;
    
        // 遍历数据数组
        data.forEach(item => {
            result={}
            const { phid_pc, take_date, take_amt } = item;
            const currentYear = new Date(take_date).getFullYear();
            const currentMonth = new Date(take_date).getMonth() + 1;
    
            // 检查当前日期是否与基准日期在同一年同一月
            if (currentYear === baseYear && currentMonth === baseMonth) {
                if (!result[phid_pc]) {
                    result[phid_pc] = {};
                }
                const monthKey = `${currentYear}-${String(currentMonth).padStart(2, '0')}`;
                if (!result[phid_pc][monthKey]) {
                    result[phid_pc][monthKey] = 0;
                }
                // 累计金额
                result[phid_pc][monthKey] += take_amt;
            }
        });
    
        return result;
    }
    // 获取项目信息
    function getPtInfoByPhid(phid,fun) {
        if (phid) {
          $NG.execServer("getPtInfoByPhid", { phid }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            fun(datas)
            // $NG.updateState((updater) => {
            //   updater.data.当前表名.setProps({
            //     //项目编码
            //     pc_no: datas.pc_no,
            //     //项目金额
            //     approx_contract_fc: datas.approx_contract_fc,
            //     //计划开工日期
            //     start_date: datas.start_date,
            //     //计划完工日期
            //     end_date: datas.end_date,
            //     //售前顾问
            //     u_sqgw: { value: datas.user_sqgw_phid, label: datas.user_sqgw_name },
            //     //项目经理
            //     u_project_manager: { value: datas.project_manager_phid, label: datas.project_manager_name },
            //     //事业部
            //     u_division: { value: datas.division_phid, label: datas.division_name },
            //     //组织
            //     phid_org_phid: { value: datas.phid_org_phid, label: datas.phid_org_name },
            //     //区域中心
            //     u_regional_center: { value: datas.regional_center_phid, label: datas.regional_center_name },
            //     //产品线
            //     user_product_line: { value: datas.midwife_phid, label: datas.midwife_name },
            //     //客户名称
            //     customer: { value: datas.customer_id, label: datas.customer_name },
            //     //部门
            //     u_dept: { value: datas.dept_phid, label: datas.dept_name },
            //     //项目类型
            //     u_pc_type: { value: datas.type_phid, label: datas.type_name },
            //     //项目预算组织编码
            //     budget_org_code: datas.budget_org_no,
            //     //项目预算组织
            //     budget_org_phid: { value: datas.budget_org_phid, label: datas.budget_org_name },
            //   });
            // });
          });
        }
      }
      
})